package elsa.tools;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.codec.Hex;

import java.security.MessageDigest;

public class CredentialsMatcher extends SimpleCredentialsMatcher {

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
        String password = new String(utoken.getPassword());
        String inPassword = md5Hex(utoken.getUsername()+password);
        //获得数据库中的密码 new String(utoken.getPassword());
        String dbPassword=(String) info.getCredentials();
        System.out.println(inPassword+"  "+dbPassword);
        //进行密码的比对
        return this.equals(inPassword, dbPassword);
    }

    //加盐密码哈希
    public static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            new Hex();
            return new String(Hex.encode(bs));
        } catch (Exception e) {
            return null;
        }
    }
}
